package com.zhiyou.aifeng.smart_machine

import android.annotation.SuppressLint
import android.os.Bundle
import android.view.View
import com.aifeng.utils.getExtra
import com.jeremyliao.liveeventbus.LiveEventBus
import com.zhiyou.aifeng.common.base.makeCall
import com.zhiyou.aifeng.common.base.oneClick
import com.zhiyou.aifeng.common.helper.*
import com.zhiyou.aifeng.common_ui.base.BaseActivity
import com.zhiyou.aifeng.common_ui.model.BaseUrl
import com.zhiyou.aifeng.common_ui.utils.showHintDialog
import com.zhiyou.aifeng.common_ui.utils.showInputDialog
import com.zhiyou.aifeng.viewmodel.OrderViewModel
import kotlinx.android.synthetic.main.activity_order_detail.*
import org.jetbrains.anko.toast
import org.json.JSONObject

class OrderDetailActivity : BaseActivity() {

    private lateinit var mOrderId: String
    private var mWorkCode: String? = null
    private var mPhone = ""
    private var mRealArea = ""
    private var mArea = ""
    private var mCount = ""

    override fun onCreate(savedInstanceState: Bundle?) {
        super.onCreate(savedInstanceState)
        setContentView(R.layout.activity_order_detail)
        initTitle(title = "详情", divider = false)

        getData()
    }

    override fun getViewModel() = get<OrderViewModel>()

    override fun initTitle(title: String, name: String, divider: Boolean) {
        super.initTitle(title, name, divider)
        mOrderId = intent.getExtra("orderId")

        order_btn1.oneClick {
            mWorkCode?.let {
                if (mPhone.isNotEmpty()) {
                    showHintDialog(
                        title = "提示",
                        hint = "确定要拨打联系农户吗？"
                    ) { makeCall(mPhone) }
                }
            }
        }
        order_btn3.oneClick {
            mWorkCode?.let {
                if (mPhone.isNotEmpty()) {
                    showHintDialog(
                        title = "提示",
                        hint = "确定要拨打联系农户吗？"
                    ) { makeCall(mPhone) }
                }
            }
        }
        order_btn2.oneClick {
            mWorkCode?.let {
                if (getString("serviceTel").isNotEmpty()) {
                    showHintDialog(
                        title = "提示",
                        hint = "确定要拨打客服电话吗？"
                    ) { makeCall(getString("serviceTel")) }
                }
            }
        }
        order_btn4.oneClick { mWorkCode?.let { startOrder(mOrderId) } }
        order_btn5.oneClick {
            mWorkCode?.let {
                endOrder(
                    mOrderId,
                    if (mCount.toNotInt() > 1) "" else mArea
                )
            }
        }
    }

    private fun startOrder(dataId: String) {
        showHintDialog(
            title = "开始作业",
            hint = "是否确认开始作业？"
        ) {
            getViewModel().request(
                requestUrl = BaseUrl.workStart,
                params = *arrayOf(
                    "uid" to getString("userId"),
                    "njsjid" to dataId
                ),
                onResult = {
                    toast("作业已开始！")
                    LiveEventBus.get("orderList").post("${dataId},3")
                    checkState("3")
                }
            )
        }
    }

    @SuppressLint("SetTextI18n")
    private fun endOrder(dataId: String, default: String) {
        showInputDialog(default) { value ->
            getViewModel().request(
                requestUrl = BaseUrl.workDone,
                params = *arrayOf(
                    "uid" to getString("userId"),
                    "njsjid" to dataId,
                    "area" to value
                ),
                onResult = {
                    toast("作业已结束！")
                    LiveEventBus.get("orderList").post("${dataId},4, $value")
                    checkState("4")

                    mRealArea = value.formatDecimal()
                    order_square01.text = "${mRealArea}亩"
                }
            )
        }
    }

    @SuppressLint("SetTextI18n")
    override fun getData(index: Int, isLoading: Boolean) {
        getViewModel().request(
            requestUrl = BaseUrl.workInfo,
            params = *arrayOf("njsjid" to mOrderId),
            onResult = {
                val obj = JSONObject(it).optJSONObject("workTask") ?: JSONObject()

                mWorkCode = obj.optNotNull("work_code")
                mCount = obj.optNotNull("count")
                mArea = obj.optNotNull("area").formatDecimal()

                order_code.text = "订单编号：$mWorkCode"
                order_type.text = obj.optNotNull("work_type_name")
                order_square.text = "${mArea}亩"
                order_time.text = obj.optNotNull("preset_date").getTimeString("yyyy-MM-dd HH:mm")
                order_adress.text =
                    obj.optNotNull("region_addr").replace(" ", "") + obj.optNotNull("address")

                mRealArea = obj.optNotNull("real_area").formatDecimal()
                order_square01.text = "${mRealArea}亩"

                mPhone = obj.optNotNull("contact_phone")
                order_name.text = obj.optNotNull("contact")
                order_tel.text = mPhone

                when (obj.optNotNull("satisfied")) {
                    "0" -> order_like.setImageResource(R.mipmap.icon_order02)
                    "1" -> order_like.setImageResource(R.mipmap.icon_order01)
                }

                val mRating = obj.optNotNull("rate").toNotFloat()
                if (mRating > 0) order_rating.rating = mRating

                checkState(obj.optNotNull("allot_state"))
            }
        )
    }

    private fun checkState(status: String) {
        order_status.text = when (status) {
            "2" -> "已接单"
            "3" -> "作业中"
            "4", "5" -> "已完成"
            else -> ""
        }

        order_square_ll.visibility = when (status) {
            "4", "5" -> View.VISIBLE
            else -> View.GONE
        }

        order_layout.visibility = when (status) {
            "5" -> View.VISIBLE
            else -> View.GONE
        }

        order_btn1.visibility = when (status) {
            "3", "4", "5" -> View.VISIBLE
            else -> View.GONE
        }

        order_btn3.visibility = when (status) {
            "2" -> View.VISIBLE
            else -> View.GONE
        }

        order_btn4.visibility = when (status) {
            "2" -> View.VISIBLE
            else -> View.GONE
        }

        order_btn5.visibility = when (status) {
            "3" -> View.VISIBLE
            else -> View.GONE
        }
    }

}